package com.cmxh.shipper.config;


import com.cmxh.shipper.util.JwtTokenUtil;
import com.cmxh.shipper.util.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * OncePerRequestFilter
 * Once:一次
 * Per:每个
 * Request：请求
 * Filter:过滤器
 *
 * 前端项目向后端发请求 每个请求都只会过一次的过滤器
 */
@Component
public class MyLoginTestFilter extends OncePerRequestFilter {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;


    @Autowired
    private RedisTemplate<String,Object> redisTemplate ;


    /**
     *
     * @param httpServletRequest  请求对象 前端发来的请求 请求参数 请求头 请求体 全部封装到这个对象中
     * @param httpServletResponse  响应对象  后端给前端响应的数据  响应参数 响应头 响应题 全部在这个对象中
     * @param filterChain  他会存储过滤器链中的所有过滤器 分1,2,3,4,5  1走完
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest,
                                    HttpServletResponse httpServletResponse,
                                    FilterChain filterChain) throws ServletException, IOException {

        try {
            // 从请求头中获取牌牌
            String authorization = httpServletRequest.getHeader("Authorization");
            System.out.println("令牌");
            System.out.println(authorization);
            // 获取请求路径
            String path = httpServletRequest.getRequestURI();
            System.out.println("Request path: " + path); // 添加日志
            // 判断请求头中是否有牌牌
            if (authorization == null||path.contains("/yanzheng")||path.contains("/zhuce")) {
                // 说明是登录
                System.out.println("说明是登录");
                // 放行登录请求
                filterChain.doFilter(httpServletRequest, httpServletResponse);
                return;
            } else {
                System.out.println("不是登录，是其他请求");
                // 检查是否是允许匿名访问的路径

                // 如果带了  我们需要进一步验证是否是合法的
                String username = jwtTokenUtil.getUserNameFromToken(authorization);
                System.out.println("username" + username);
                if (username != null) {
                    // 说明 解析正确
                    System.out.println("解析正确");
                    // 去redis中取登录这个人的角色和权限
                    LoginUser o = (LoginUser) redisTemplate.opsForValue().get(username);
                    System.out.println(o);


                    // 登录对象
//                Collection
//                        <? extends GrantedAuthority>
//                List<GrantedAuthority> quanxians = new ArrayList<>();
//                List<String> quanxianandroles = o.getQuanxianandroles();
//                // 遍历第二个集合
////                for (String s:quanxianandroles){
////                    GrantedAuthority hh = new SimpleGrantedAuthority(s);
////                    quanxians.add(hh);
////                }

                    if(o!=null&&o.getPwd()!=null){
                        // stream流
                        List<SimpleGrantedAuthority> collect = new ArrayList<>();

//
                        UsernamePasswordAuthenticationToken xx = new UsernamePasswordAuthenticationToken(username, o.getPwd(),collect);
                        SecurityContext context = SecurityContextHolder.getContext();
//                // setAuthentication(需要一个实现了Authentication对象)
                        context.setAuthentication(xx);
                    }else{
                        // stream流
                        List<SimpleGrantedAuthority> collect = new ArrayList<>();

//
                        UsernamePasswordAuthenticationToken xx = new UsernamePasswordAuthenticationToken(username, "",collect);
                        SecurityContext context = SecurityContextHolder.getContext();
//                // setAuthentication(需要一个实现了Authentication对象)
                        context.setAuthentication(xx);
                    }
//
//

                    // 放行

                } else {
                    // 说明解析失败
                    System.out.println("解析失败");
                }
                filterChain.doFilter(httpServletRequest, httpServletResponse);
            }


        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}
